<template>
  <div>


    <div class="calculate setinput" >
      <li>试算：<el-input v-model="calculateExpression"></el-input>
        <el-button @click="calculate">试算</el-button></li>

      <li>结果：{{calcaulateValue}}</li>
    </div>

    <div class="selectwidth">
      zip包： <el-select v-model="zipselect" placeholder="请选择压缩包" size="medium" @change="getFilesContent"  :disabled="!submitFlag" >
        <el-option
          v-for="(item,index) in zipdtos"
          :key="item.id"
          :label="item.name"
          :value="index">
        </el-option>
      </el-select>

    </div>

    <div class="selectwidth">
      <li>  <el-checkbox v-model="iscwbw">是否财务报文</el-checkbox> </li>
     xml: <el-select v-model="xmlselect" placeholder="请选择xml" size="medium" @change="getFileObject" :disabled="!saveFlag">
        <el-option
          v-for="(item,index) in zipfiles"
          :key="index"
          :label="item.name"
          :value="index">
        </el-option>
      </el-select>

    </div>

    <div>

      <div>需要修改的key {{fileString}}

        <div style="border:1px  ">值：
          <el-button type="primary"  size="mini" @click="addNewTask(tasks)">新增</el-button>

          <el-table :data="tasks">
            <el-table-column label="key">
              <template slot-scope="{row,index}">
                <span v-show="!row.editable" @dblclick="edit(row,index)">{{row.key }}</span>
                <el-input  v-show="row.editable" v-model="row.key"></el-input>
              </template>
            </el-table-column>


            <el-table-column
              type="index"
              width="50">

              <template slot-scope="{row,$index}">
                <span v-show="!row.editable">{{$index+1}}</span>
                <el-button v-show="row.editable" type="primary" icon="el-icon-check" size='mini'
                           @click=updatetask(row)></el-button>
                <el-button class="marginleftset" v-show="row.editable" type="primary" icon="el-icon-close" size='mini'
                           @click=deletetask($index,row)></el-button>

              </template>
            </el-table-column>
            <el-table-column label="value">
              <template slot-scope="{row,index}">
                <span v-show="!row.editable" @dblclick="edit(row,index)">{{row.value }}</span>
                <el-input  v-show="row.editable" v-model="row.value"></el-input>
                <!-- <span v-show="!row.editable" @dblclick="edit(row,index)">{{row.executor}}</span>
                 <el-input v-show="row.editable"  v-model="row.executor.toString()"  ></el-input>-->

              </template>
            </el-table-column>

            <el-table-column label="confirm">
              <template slot-scope="{row,index}">
                <!-- <span v-show="!row.editable" @dblclick="edit(row,index)">{{row.executor}}</span>
                 <el-input v-show="row.editable"  v-model="row.executor.toString()"  ></el-input>-->
                <el-button type="primary" size="mini" @click="edit(row,index)" v-show="!row.editable">修改</el-button>
                <el-button type="primary" size="mini" @click="updateValue(row,index)" v-show="row.editable">确定</el-button>
              </template>
            </el-table-column>

          </el-table>
    </div>

        <div><el-button  @click="savexml"  icon="el-icon-download" type="primary">保存此xml</el-button>
          <el-button  @click="submitChange"  icon="el-icon-download" type="primary">提交修改</el-button>
          <el-button  @click="downLoadFile"  icon="el-icon-download" type="primary">下载zip包</el-button>

          <el-button  @click="resetall"  icon="el-icon-download" type="primary">重置所有</el-button></div>

      </div>


      <hr>


      <el-button   v-loading="loading"
                   element-loading-text="拼命加载中"
                   element-loading-spinner="el-icon-loading"
                   element-loading-background="rgba(0, 0, 0, 0.8)"  @click="send"  icon="el-icon-download" type="primary">发送请求</el-button>

      <ol>
        <li>zip包名: <span>{{repContent.zipname}}</span></li>
        <li>xml修改记录: <span> {{repContent.filechange}}</span></li>
        <li>修改后zip路径：<span>{{zipfileurl.path}}</span></li>
        <li>返回值: <span></span></li>

      </ol>
         <div v-if="repContent.repContent  && repContent.repContent[0].errorMsg"> {{repContent.repContent[0].errorMsg}}</div>
        <div  v-else-if="repContent.repContent  && repContent.repContent[0]" >

          <ol>
            <li> 档案号：{{repContent.repContent[0].djxh}}</li>
            <li> 错误规则数量：{{repContent.repContent[0].ruleErrorCount}}</li>
            <li> 征期ID：{{repContent.repContent[0].zqId}}</li>
            <li> 检测规则数量：{{repContent.repContent[0].ruleCount}}</li>
            <li> 校验时间：{{repContent.repContent[0].createDate}}</li>
          </ol>
          <div>
            <span   class="setinput"> 查询：  <el-input v-model="tablesearch" size="mini"></el-input></span>

            <el-table
              :data="repContent.repContent[0].ruleResults.filter(data => !tablesearch || data.ruleId.toString().includes(tablesearch.toLowerCase()))"
              style="width: 100%">

              <el-table-column
                label="规则名称"
                prop="xmmc" width="100px">
              </el-table-column>

              <el-table-column
                label="规则id"
                prop="ruleId"  width="200px">
              </el-table-column>

              <el-table-column
                label="概述"
                prop="ywms"  width="200px">
              </el-table-column>

              <el-table-column
                label="风险等级"
                prop="fxdj" width="40px">
              </el-table-column>

              <el-table-column
                label="规则执行结果值"
                prop="resultValue"  width="50px">

                <template slot-scope="scope">


                  <pre>{{ scope.row.resultValue ?'通过' : '不通过'}}</pre>

                </template>

              </el-table-column>

              <el-table-column
                label="检测结果"
                prop="jcjg"    width="40px">
              </el-table-column>

              <el-table-column
                label = "错误信息"

              >

                <template slot-scope="scope">


                  <pre>{{ scope.row.ruleTip  }}</pre>

                </template>
              </el-table-column>
            </el-table>




          </div>



        </div>





    </div>

  </div>

</template>

<script>
import {uploadzip , getZipList,getFileContents,submitfiles,downloadzip,sendzip}  from '../../api/shuiyoustools'
import Xml2js from 'xml2js'
import $ from 'jquery'
import  vue from 'vue'
import jsonpath from 'advanced-json-path'
  export default {
    name: "xmlParseUpload",
    data(){
      return {
        downloadURL: '',

        uploadURL:'',
        uploadData:{user:"dfdfdfd"},
        filenames:[],
        zipselect:'',
        xmlselect:'',
        selectziptype : '',


        tablesearch : '',
        zipdtos : [],


        zipfiles : [],


        saveFlag : true,
        submitFlag : true,

        repContent : '',

        zipfileurl:'', // 用于修改完文件后 将修改后的zip下载下来（仅临时使用，防止发送zip接口来不及完成的情况）

        fileString:"121212",
        xmlObject: {},
        filename:'',
        subxmlObject:{},
        tasks:[],
        express:'',
        keys:[],
        iscwbw:false,
        cjbdxmlExpression:'$.taxML.SB100VO.SB100BdxxVO.cjbdxml',//写死
        cjbdxmlExpressionNoJsonPath : 'taxML.SB100VO.SB100BdxxVO.cjbdxml',

        loading: false,
        changeRecord:{
          zipname:'',
          filechange:[  {
            filename: '',
            change:[]
          }],
          repContent:''
        },


        calculateExpression :'',
        calcaulateValue : '',

      };
    },
    methods:{
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
       // return this.$confirm(`确定移除 ${ file.name }？`);
      },
      submit(e){
        console.log(e)

        this.$notify({
          title: '提示',
          message: '这是一条不会自动关闭的消息',
          duration: 0
        });


      },
      /**
       * 获取上传文件子文件名
       */
      onsuccess(rep){
        this.$notify({
          title: '提示',
          message: rep,

        });
      },

      getziplist(){
        console.log("=====")
        getZipList()
          .then(res => {
            console.log(res)
            this.zipdtos = res.data
        }).catch(err => {
          this.$alert(err.data, 'error')
        })
      },



      getFilesContent(index){
        this.selectziptype = this.zipdtos[this.zipselect].type
        console.log(index)
        getFileContents(this.zipdtos[index])
          .then(rep=>{
            this.zipfiles = rep.data



          }).catch(err => {
          this.$alert(err.data, 'error')
          return;
        })

      this.submitFlag = false
       // this.repContent = '';
        this.changeRecord =
          {


              zipname:'',
              filechange:[],
              repContent:''


          };

        this.changeRecord.zipname = this.zipdtos[this.zipselect].name

      },

      /**
       * 将 content 内容转为 json,并存储到xmlobject 中,
       * @param value
       */
      getFileObject(index){
        console.log(this.xmlselect)
        console.log('change'+ index)

        this.readXml(this.zipfiles[index])

        this.saveFlag = false

      },


      getUploadUrl(){
        console.log("getuploadurl")
        //this.downloadURL = downloadzip()
        this.uploadURL = uploadzip()
        //return 'https://jsonplaceholder.typicode.com/posts/'
      },

      executorListchange(){
        this.readXml()
        this.tasks = []


      },
      readXml(value){
        let xmlParser = new Xml2js.Parser({explicitArray: false, ignoreAttrs: false});

        let that = this







        var promise = new Promise(((resolve, reject) => {



            xmlParser.parseString(value.content,function (err,rep) {
              if (null!= err){console.log(err);return}
              resolve(rep)
            })

        }))
        promise.then(value =>{
          console.log(value)
          this.xmlObject = value

          //this.fileString = this.xmlObject.taxML.ywbw.A100000.zbForm.yysr

          //  console.log(jsonpath(value,'$.taxML.ywbw.A100000.zbForm.yysr'))
        }).then(()=>{
          let needXmlbw =''
          if(this.iscwbw){
            needXmlbw = jsonpath(this.xmlObject,this.cjbdxmlExpression)
            //  console.log(needXmlbw)
            new Promise((resolve, reject) => {
              let xmlParser = new Xml2js.Parser({explicitArray: false, ignoreAttrs: false});
              //  console.log(needXmlbw)
              xmlParser.parseString(needXmlbw,function (err,rep) {
                if (null!= err) {
                  that.warn('请确认报文类型，再重新上传文件')
                  // warn()
                  console.log(err);return}
                resolve(rep)
              })

            }).then(value => {

              //  console.log(value)
              this.subxmlObject = value ;  console.log(JSON.stringify(this.subxmlObject))

            })

          }

        })

      },

      savexml(){



        if (JSON.stringify(this.xmlObject) == '{}') return;
        let xmlBuild = new Xml2js.Builder();
        let subxml;
        if (this.iscwbw){
          subxml =  xmlBuild.buildObject(this.subxmlObject)
          this.setValue(this.cjbdxmlExpressionNoJsonPath,this.xmlObject,subxml)
        }

        let xml = xmlBuild.buildObject(this.xmlObject);
        console.log(this.xmlselect)

        let xmlchange = {filename:'',change:[]}
            xmlchange.filename = this.zipfiles[this.xmlselect].name
            xmlchange.change =(JSON.parse(JSON.stringify(this.tasks)))
        this.changeRecord.filechange.push(xmlchange)


        this.zipfiles[this.xmlselect].content = xml
        this.saveFlag = true
        this.tasks = []
        this.xmlObject = {}

        this.subxmlObject = {}
        this.xmlselect = '';



      },
      submitChange(){
          if (!this.saveFlag  ){

            this.$alert('请先保存xml修改', '标题名称', {
              confirmButtonText: '确定',
              callback: action => {
                this.$message({
                  type: 'info',
                  message: '请先保存xml修改'
                });
              }
            });
            return;

          }
          if ( this.zipfiles.length == 0 ){

            this.$alert('请重新选择zip文件', '标题名称', {
              confirmButtonText: '确定',
              callback: action => {
                this.$message({
                  type: 'info',
                  message: '请重新选择zip文件'
                });
              }
            });
            return;

          }

        submitfiles(this.zipdtos[this.zipselect].id,this.zipfiles)
          .then(rep=>{
            this.zipfileurl = rep.data
            console.log(this.zipfileurl)
          }).catch(err=>{
          this.$alert(err.data, 'error')
          return;
        })


        this.zipselect = ''
        this.submitFlag = true
        this.zipfiles = []

      },
      send(){
        this.loading = true
        let params = {
          typeid : this.selectziptype,
          path : this.zipfileurl.path
        }
          sendzip( params)
            .then(rep=>{
              console.log(JSON.stringify(rep.data).replace(/\\/g,""))

             // JSON.parse(JSON.stringify(rep.data).replace(/\\/g,""))



              this.changeRecord.repContent = JSON.parse(rep.data)
             // this.repContent =  JSON.stringify(this.changeRecord).replace(/\\/g,"")
              this.repContent = this.changeRecord
              this.loading =false
            })




      },
      verifyRep(){

      },


      resetall(){
        this.tasks = []
        this.zipfiles = []
        this.saveFlag = true
        this.submitFlag = true
        this.subxmlObject = {}
        this.xmlObject = {}
        this.zipselect = ''
        this.xmlselect = ''
        this.changeRecord = ''
        this.repContent = ''

      },
      getziffileIndex(value){

        for (let index in this.zipfiles){
          console.log(index)
          if (this.zipfiles[index].id = value.id) {
            return index;
          }
        }


      },




      downLoadFile(){
  /*      if (JSON.stringify(this.xmlObject) == '{}') return;
        let xmlBuild = new Xml2js.Builder();
        let subxml;
        if (this.iscwbw){
          subxml =  xmlBuild.buildObject(this.subxmlObject)
          this.setValue(this.cjbdxmlExpressionNoJsonPath,this.xmlObject,subxml)
        }

        let xml = xmlBuild.buildObject(this.xmlObject);
        console.log(xml)

        console.log("downloadfile")
        let content = xml
        let fileName= this.filename
        let aTag = document.createElement('a');
        let blob = new Blob([content]);　　// 这个content是下载的文件内容，自己修改
        aTag.download = fileName;　　　　　　// 下载的文件名
        aTag.href = URL.createObjectURL(blob)

        aTag.click();
        URL.revokeObjectURL(blob)*/


      let param = {
        fileName : this.zipfileurl.path
      }
      downloadzip(param)
        .then(rep=>{
          console.log(rep)
          let fileName= "121212.zip"
          let aTag = document.createElement('a');
          let blob = new Blob([rep.data]);　　// 这个content是下载的文件内容，自己修改
           aTag.download = this.zipfileurl.filename;　　　　　　// 下载的文件名
          aTag.href = URL.createObjectURL(blob)

          aTag.click();
          URL.revokeObjectURL(blob)
        })


      },

      calculate(){
        console.log(this.calculateExpression )
        this.calcaulateValue =eval(this.calculateExpression )
        console.log(this.calcaulateValue)
        return eval(this.calculateExpression )
      },

      getkey(){
        console.log('====')
        let extmp = this.keyCalibration(this.express,this.iscwbw ?this.subxmlObject : this.xmlObject)
        extmp = '$.'+extmp
        console.log(extmp)
        console.log(JSON.stringify(jsonpath(this.iscwbw ?this.subxmlObject : this.xmlObject,extmp)))


        //   console.log(this.keys)
      },

      updateValue(row,index){  //获取对应的key值  ，如表达式出错 则异常提示
        vue.delete(row,'editable')
        this.setValue(row.key, this.iscwbw ?this.subxmlObject : this.xmlObject,row.value)
        console.log(JSON.stringify(this.iscwbw ?this.subxmlObject : this.xmlObject))
      },


      addNewTask(tasks){
        let newtask={

          key:'',
          value:'',
          editable:true
        }
        tasks.push(newtask)
      },

      edit(value2, index) {
        vue.set(value2, 'editable', true)
      },

      deletetask(index,row){

        this.tasks.splice(index,1)
        // return

        // vue.delete(row,'editable')

      },
      updatetask(row) {
        // if(row.name != '' && row.name )

        // this.row.key =  this.keyCalibration(row.key.trim(),this.xmlObject)
        vue.set(row,'key',this.keyCalibration(row.key.trim(),this.iscwbw ?this.subxmlObject : this.xmlObject))
        vue.delete(row, 'editable')

        vue.set(row,'value',this.findValue(row.key.trim(),this.iscwbw ?this.subxmlObject : this.xmlObject))



      },

      findValue (expression,obj) {

        let arr = expression.replace(/\"/g,'').split(',')
        let j =obj

        if (arr.length > 1){// 'xml.key.value,"aa","a","bb'


          let searchkey = arr[1]
          let searchValue = arr[2]
          let changekey = arr[3]
          let subarr = arr[0].split('.');
          let isFindSearchValue = false;
          for (let i in subarr){
            j=j[subarr[i]]
          }
          console.log(j )


          for (let i in j){
            if (j[i][searchkey] == searchValue){

              j= j[i][changekey]
              isFindSearchValue = true
              break
            }
          }

          if (!isFindSearchValue){
            this.warn(`未发现值为${searchValue}的键${searchkey}`)
            return
          }

        } else {    // xml.key.value2

          let subarr =   expression.split('.')

          for (let i in subarr){

            j=j[subarr[i]]
          }


        }

        return j
      },


      setValue(expression,obj,updatevalue) {

        //如果为isnotequal时




        let arr = expression.replace(/\"/g,'').split(',')
        let j =obj

        if (arr.length > 1){              // 'xml.key.value,"aa","a","bb'
          let subarr = arr[0].split('.')

          for (let i in subarr){
            j=j[subarr[i]]
          }

          for (let i in j){
            let key = arr[1]
            let searchValue = arr[2]
            let changekey = arr[3]

            if (j[i][key] == searchValue){

              j[i][changekey] = updatevalue
              return
            }
          }

        } else {    // xml.key.value2

          let subarr =   expression.split('.')

          for (let i in subarr){
            console.log(updatevalue)
            console.log(i)
            if (i== subarr.length-1){
              console.log('============')
              j[subarr[i]]=updatevalue
              return
            }
            j=j[subarr[i]]
          }

        }

      },

      keyCalibration  (expression,obj) {  //根据  json中大小写 来校准  expression 中的key值

        let startStr = 'taxML'

        console.log('keyCalibration contains')
        console.log(expression)
        console.log(obj)


        // console.log(!expression.toLowerCase().startsWith(startStr.toLowerCase()))
        if (!expression.toLowerCase().startsWith(startStr.toLowerCase())) {
          expression = 'taxML.'+expression
          console.log('expression:'+expression)
        }




        let arr = expression.replace(/\"/g,'').split(',')
        let subarr = arr[0].split('.')
        let objtmp = obj
        let isFindKey = true

        for (let i in subarr){   //校准subarr
          if (!isFindKey && i>0){
            //执行 没有发现key  未发现
            this.warn('找不到对应键值：'+subarr[i-1])
            return
          }
          let keys = this.getObjkey(objtmp)
          for(let j in keys){
            isFindKey  = false

            if (keys[j].toLowerCase() == subarr[i].toLowerCase()){
              subarr[i]=keys[j]
              objtmp = objtmp[keys[j]]
              console.log('=================这里是keycall============')
              isFindKey = true
              break
            }


          }



        }

        if (!isFindKey  ){
          //执行 没有发现key  未发现
          this.warn('找不到键值：'+arr[0])
          return
        }





        if (arr.length >1){
          //校准 二维数据
          let flag =0

          let keys = this.getObjkey(objtmp[0])
          console.log('输出扫描的二维key')
          for (let j in keys){
            console.log(keys[j])
            if (keys[j].toLowerCase() == arr[1].toLowerCase()){
              arr[1] = keys[j]
              flag++

            }
            if (keys[j].toLowerCase() == arr[3].toLowerCase()){
              arr[3] = keys[j]
              flag++
            }

            if (flag == 2 ){
              break
            }

          }



          if (flag <2 ){
            //执行 没有发现key  未发现
            this.warn('找不到对应键值：'+arr[1] +'或' + arr[3])

            return
          }
        }


        //重新组装
        let newEXpre = ''
        for (let index in subarr){
          if (subarr.length -1 == index) {
            newEXpre = newEXpre + subarr[index]
          }else{
            newEXpre = newEXpre + subarr[index]+'.'
          }


        }
        for(let i =1 ; i<arr.length ;i++){
          newEXpre = newEXpre +','+ arr[i]
        }



        return newEXpre

      },

      getObjkey (obj) {
        let arr=[]
        for (let i in obj){
          arr.push(i)
        }

        return arr
      },


      warn(message) {
        this.$alert(message, '标题名称', {
          confirmButtonText: '确定',
          callback: action => {
            this.$message({
              type: 'info',
              message: `action: ${ action }`
            });
          }
        });
      }

    },
    mounted(){
       this.getUploadUrl(),
        this.getziplist()
    },
    computed:{

    }

  }
</script>

<style scoped>

  .selectwidth >>> .el-select {
    display: inline-block;
    position: relative;
    width:500px;
  }


  .setinput >>> .el-input {


    position: relative;

    font-size: 14px;

    display: inline-block;

    width: 50%;

  }

  .calculate {
    width: 500px;
    float: right;
  }

  pre{
    white-space:pre-wrap; /* css3.0 */
    white-space:-moz-pre-wrap; /* Firefox */

    white-space:-o-pre-wrap; /* Opera 7 */
    word-wrap:break-word; /* Internet Explorer 5.5+ */
  }


</style>
